<?php
/**
 * Created by PhpStorm.
 * User: wenjoying@126.com
 * Date: 2018/5/31
 * Time: 10:16
 */

namespace App\Models;

use App\Http\Scopes\EnableScope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    const COL_ID = 'id';
    const COL_UUID = 'uuid';
    const COL_USER_ID = 'user_id';
    const COL_ADMIN_ID = 'admin_id';
    const COL_IS_ENABLE = 'is_enable';

    /**
     * 自动应用全局作用域,限制返回有效结果
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

//        static::addGlobalScope(new EnableScope());
    }

    /**
     * 手动应用全局作用域,限制返回有效结果
     * @param $query
     * @return mixed
     */
    public function scopeIsEnable(Builder $query)
    {
        return $query->where('is_enable', 1);
    }

    /**
     * 手动应用全局作用域,返回排序
     * @param $query
     * @param $order
     * @param $field
     * @return mixed
     */
    public function scopeSortBy(Builder $query, $field='', $order='DESC')
    {
        $field = $field ?? self::CREATED_AT;
        return $query->orderBy($field, $order);
    }

    /**
     * 返回关联表指定字段
     * @param $query
     * @param $relation
     * @param array $columns
     * @return mixed
     */
    public function scopeWithColumns(Builder $query, $relation, Array $columns)
    {
        return $query->with([$relation => function ($query) use ($columns){
            $query->select($columns);
        }]);
    }



}
